//
//  MsgManager.m
//  FootPrint
//
//  Created by alex tao on 5/7/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "MsgManager.h"

#define SAFE(obj)   ((obj)?(obj):@" ")

@implementation MsgManager

static MsgManager * _sharedInstance = nil;

+ (MsgManager*) sharedInstance
{
	if (_sharedInstance == nil) {
        _sharedInstance = [[MsgManager alloc] init];
    }
	return _sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self loadIndex];
    }
    return self;
}

- (void)dealloc

{   [_eventList release];
    [_inviteList release];
    [_merchantList release];
    [_urlList release];
    [_rootDict release];
    [super dealloc];
}

- (NSString *)rootDirectory
{
    if (nil == _rootDict) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        
        _rootDict = [[baseDir stringByAppendingPathComponent:@"PushMsg"] copy];
    }
    
    NSString * realPath = [_rootDict stringByAppendingFormat:@"/%lld", [GConfig getUserId]];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:realPath])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:realPath
                                  withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return realPath;
}

- (NSString*) pushMsgFileForName:(NSString*)name
{
    return [NSString stringWithFormat:@"%@/%@", [self rootDirectory], name];
}

- (void) loadIndex
{
    _eventList = [[NSMutableArray alloc] initWithContentsOfFile:[self pushMsgFileForName:@"pushEvent.idx"]];
    if (nil == _eventList) {
        _eventList = [[NSMutableArray alloc] initWithCapacity:4];
    }
    
    _inviteList = [[NSMutableArray alloc] initWithContentsOfFile:[self pushMsgFileForName:@"pushInvite.idx"]];
    if (nil == _inviteList) {
        _inviteList = [[NSMutableArray alloc] initWithCapacity:4];
    }
    
    _merchantList = [[NSMutableArray alloc] initWithContentsOfFile:[self pushMsgFileForName:@"pushMerchant.idx"]];
    if (nil == _merchantList) {
        _merchantList = [[NSMutableArray alloc] initWithCapacity:4];
    }
    
    _urlList = [[NSMutableArray alloc] initWithContentsOfFile:[self pushMsgFileForName:@"pushUrl.idx"]];
    if (nil == _urlList) {
        _urlList = [[NSMutableArray alloc] initWithCapacity:4];
    }
}

- (void) saveIndex
{
    [_eventList writeToFile:[self pushMsgFileForName:@"pushEvent.idx"] atomically:YES];
    [_inviteList writeToFile:[self pushMsgFileForName:@"pushInvite.idx"] atomically:YES];
    [_merchantList writeToFile:[self pushMsgFileForName:@"pushMerchant.idx"] atomically:YES];
    [_urlList writeToFile:[self pushMsgFileForName:@"pushUrl.idx"] atomically:YES];
}

- (void)removeDuplicate
{
    {
        NSMutableArray * newList = [[NSMutableArray alloc] initWithCapacity:8];
        for (NSDictionary * dict in _eventList) {
            BOOL isNew = YES;
            for (NSDictionary * endDict in newList) {
                if ([[dict objectForKey:@"eventId"] isEqualToString:[endDict objectForKey:@"eventId"]])
                {
                    isNew = NO;
                    break;
                }
            }
            if (isNew) {
                [newList addObject:dict];
            }
        }
        [_eventList removeAllObjects];
        [_eventList addObjectsFromArray:newList];
    }

    {
        NSMutableArray * newList = [[NSMutableArray alloc] initWithCapacity:8];
        for (NSDictionary * dict in _inviteList) {
            BOOL isNew = YES;
            for (NSDictionary * endDict in newList) {
                if ([[dict objectForKey:@"userId"] isEqualToString:[endDict objectForKey:@"userId"]] &&
                    [[dict objectForKey:@"content"] isEqualToString:[endDict objectForKey:@"content"]] )
                {
                    isNew = NO;
                    break;
                }
            }
            if (isNew) {
                [newList addObject:dict];
            }
        }
        [_inviteList removeAllObjects];
        [_inviteList addObjectsFromArray:newList];
    }
    
    {
        NSMutableArray * newList = [[NSMutableArray alloc] initWithCapacity:8];
        for (NSDictionary * dict in _merchantList) {
            BOOL isNew = YES;
            for (NSDictionary * endDict in newList) {
                if ([[dict objectForKey:@"merchantId"] isEqualToString:[endDict objectForKey:@"merchantId"]] &&
                    [[dict objectForKey:@"title"] isEqualToString:[endDict objectForKey:@"title"]] &&
                    [[dict objectForKey:@"content"] isEqualToString:[endDict objectForKey:@"content"]])
                {
                    isNew = NO;
                    break;
                }
            }
            if (isNew) {
                [newList addObject:dict];
            }
        }
        [_merchantList removeAllObjects];
        [_merchantList addObjectsFromArray:newList];
    }
    
    {
        NSMutableArray * newList = [[NSMutableArray alloc] initWithCapacity:8];
        for (NSDictionary * dict in _urlList) {
            BOOL isNew = YES;
            for (NSDictionary * endDict in newList) {
                if ([[dict objectForKey:@"title"] isEqualToString:[endDict objectForKey:@"title"]] &&
                    [[dict objectForKey:@"url"] isEqualToString:[endDict objectForKey:@"url"]] )
                {
                    isNew = NO;
                    break;
                }
            }
            if (isNew) {
                [newList addObject:dict];
            }
        }
        [_urlList removeAllObjects];
        [_urlList addObjectsFromArray:newList];
    }
}

+ (NSDictionary*) makeEventMsg:(long long)eventId andTitle:(NSString*)title andUrl:(NSString*)imgUrl
{
    NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
    
    [dict setObject:L2S(eventId) forKey:@"eventId"];
    [dict setObject:SAFE(title) forKey:@"eventName"];
    if (imgUrl) [dict setObject:imgUrl forKey:@"imgUrl"];
    [dict setObject:@"event" forKey:@"type"];
    
    return dict;
}

+ (NSDictionary*) makeInviteMsg:(long long)userId
{
    NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
    
    [dict setObject:L2S(userId) forKey:@"userId"];
    [dict setObject:@"invite" forKey:@"type"];
    
    return dict;
}

- (void)mergeInfo:(InfoQueryResponseMessage*)info
{
    if(info && [info resultCode]==0)
    {
        EventQueryResponseMessage* evtMsg = [info event];
        FriendInvitationResponseMessage* friendMsg = [info friendInvitation];
        
        PBArray* arrEvent = [evtMsg eventSumList];
        for (int i = 0; i < arrEvent.count; i++) {
            EventQueryResponseMessage_Summary * obj = [arrEvent objectAtIndex:i];
            
            NSDictionary * dict = [MsgManager makeEventMsg:obj.eventId andTitle:obj.eventName andUrl:obj.imgUrl];

            [_eventList insertObject:dict atIndex:0];
        }
        
        PBArray* arrFriend = [friendMsg invitationList];
        for (int i = 0; i < arrFriend.count; i++) {
            FriendInvitationResponseMessage_Invitation * obj = [arrFriend objectAtIndex:i];

            NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
            [dict setObject:SAFE(obj.content) forKey:@"content"];
            [dict setObject:SAFE(obj.user.phone) forKey:@"phone"];
            [dict setObject:L2S(obj.user.id) forKey:@"userId"];
            [dict setObject:SAFE(obj.user.nickName) forKey:@"nickName"];
            [dict setObject:I2S((int)(obj.user.portrait.isSys)) forKey:@"isSys"];
            [dict setObject:L2S(obj.user.portrait.id) forKey:@"imgId"];
            if (obj.user.portrait.imageUrl) [dict setObject:obj.user.portrait.imageUrl forKey:@"imgUrl"];
            [dict setObject:@"invite" forKey:@"type"];
            
            [_inviteList insertObject:dict atIndex:0];
        }
        
        PBArray* arrMerchant = [info merchantEventList];
        for (int i = 0; i < arrMerchant.count; i++) {
            InfoQueryResponseMessage_MerchantEvent * obj = [arrMerchant objectAtIndex:i];
            
            NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
            [dict setObject:SAFE(obj.title) forKey:@"title"];
            [dict setObject:SAFE(obj.eventContent) forKey:@"content"];
            [dict setObject:L2S(obj.merchant.id) forKey:@"merchantId"];
            [dict setObject:SAFE(obj.merchant.name) forKey:@"merchantName"];
            [dict setObject:I2S((int)(obj.merchant.logo.isSys)) forKey:@"isSys"];
            [dict setObject:L2S(obj.merchant.logo.id) forKey:@"imgId"];
            if (obj.merchant.logo.imageUrl) [dict setObject:obj.merchant.logo.imageUrl forKey:@"imgUrl"];
            [dict setObject:L2S(obj.deadline) forKey:@"deadline"];
            [dict setObject:@"merchant" forKey:@"type"];

            [_merchantList insertObject:dict atIndex:0];
        }
        
        PBArray* arrUrl = [info urlList];
        for (int i = 0; i < arrUrl.count; i++) {
            InfoQueryResponseMessage_UtlList * obj = [arrUrl objectAtIndex:i];
            
            NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
            [dict setObject:SAFE(obj.title) forKey:@"title"];
            [dict setObject:obj.url forKey:@"url"];
            if (obj.imageUrl) [dict setObject:obj.imageUrl forKey:@"imgUrl"];
            [dict setObject:L2S(obj.deadline) forKey:@"deadline"];
            [dict setObject:@"url" forKey:@"type"];
            
            [_urlList insertObject:dict atIndex:0];
        }
        
        //       urlImg = [[resp urlListAtIndex:0]imageUrl];
        //       urlTitle = [[resp urlListAtIndex:0] title];
        //       urlDeadL = [[resp urlListAtIndex:0]deadline]; yyyymmdd格式
        //把这些数据添加到本地缓存，并刷新tableView
        //事件显示事件图片+事件名称，好友显示好头头相+好友名称
        //商户显示商户图片+商户名，URL显示urlImg+urlTitle
        
        [self removeDuplicate];
        
        [self saveIndex];
        
    }
}

- (NSArray*) pushMsgOfName:(NSString*)name
{
    if ([name isEqualToString:@"event"]) {
        return [_eventList copy];
    } else if ([name isEqualToString:@"invite"]) {
        return [_inviteList copy];
    } else if ([name isEqualToString:@"merchant"]) {
        return [_merchantList copy];
    } else if ([name isEqualToString:@"url"]) {
        return [_urlList copy];
    }
    
    return nil;
}

- (void) addMsg:(NSDictionary*)msg
{
    [self removeMsg:msg];
    
    NSString * type = [msg objectForKey:@"type"];
    if ([type isEqualToString:@"event"])
    {
        [_eventList insertObject:msg atIndex:0];
        [_eventList writeToFile:[self pushMsgFileForName:@"pushEvent.idx"] atomically:YES];
    }
    else if ([type isEqualToString:@"invite"])
    {
        [_inviteList insertObject:msg atIndex:0];
        [_inviteList writeToFile:[self pushMsgFileForName:@"pushInvite.idx"] atomically:YES];
    }
    else if ([type isEqualToString:@"merchant"])
    {
        [_merchantList insertObject:msg atIndex:0];
        [_merchantList writeToFile:[self pushMsgFileForName:@"pushMerchant.idx"] atomically:YES];
        
    }
    else if ([type isEqualToString:@"url"])
    {
        [_urlList insertObject:msg atIndex:0];
        [_urlList writeToFile:[self pushMsgFileForName:@"pushUrl.idx"] atomically:YES];
    }
}

- (void) removeMsg:(NSDictionary*)msg
{
    NSString * type = [msg objectForKey:@"type"];
    if ([type isEqualToString:@"event"])
    {
        NSDictionary * rmObj = nil;
        for (NSDictionary * dict in _eventList) {
            if ([[dict objectForKey:@"eventId"] isEqualToString:[msg objectForKey:@"eventId"]])
            {
                rmObj = dict;
                break;
            }
        }
        if (rmObj) {
            [_eventList removeObject:rmObj];
            [_eventList writeToFile:[self pushMsgFileForName:@"pushEvent.idx"] atomically:YES];
        }
    }
    else if ([type isEqualToString:@"invite"])
    {
        NSDictionary * rmObj = nil;
        for (NSDictionary * dict in _inviteList) {
            if ([[dict objectForKey:@"userId"] isEqualToString:[msg objectForKey:@"userId"]])
            {
                rmObj = dict;
                break;
            }
        }
        if (rmObj) {
            [_inviteList removeObject:rmObj];
            [_inviteList writeToFile:[self pushMsgFileForName:@"pushInvite.idx"] atomically:YES];
        }
    }
    else if ([type isEqualToString:@"merchant"])
    {
        NSDictionary * rmObj = nil;
        for (NSDictionary * dict in _merchantList) {
            if ([[dict objectForKey:@"merchantId"] isEqualToString:[msg objectForKey:@"merchantId"]] &&
                [[dict objectForKey:@"title"] isEqualToString:[msg objectForKey:@"title"]] &&
                [[dict objectForKey:@"content"] isEqualToString:[msg objectForKey:@"content"]])
            {
                rmObj = dict;
                break;
            }
        }
        if (rmObj) {
            [_merchantList removeObject:rmObj];
            [_merchantList writeToFile:[self pushMsgFileForName:@"pushMerchant.idx"] atomically:YES];
        }
    }
    else if ([type isEqualToString:@"url"])
    {
        NSDictionary * rmObj = nil;
        for (NSDictionary * dict in _urlList) {
            if ([[dict objectForKey:@"title"] isEqualToString:[msg objectForKey:@"title"]] &&
                [[dict objectForKey:@"url"] isEqualToString:[msg objectForKey:@"url"]] )
            {
                rmObj = dict;
                break;
            }
        }
        if (rmObj) {
            [_urlList removeObject:rmObj];
            [_urlList writeToFile:[self pushMsgFileForName:@"pushUrl.idx"] atomically:YES];
        }
    }
}

- (BOOL) isMsgExist:(NSDictionary*)msg
{
    NSString * type = [msg objectForKey:@"type"];
    if ([type isEqualToString:@"event"])
    {
        for (NSDictionary * dict in _eventList) {
            if ([[dict objectForKey:@"eventId"] isEqualToString:[msg objectForKey:@"eventId"]])
            {
                return YES;
            }
        }
    }
    else if ([type isEqualToString:@"invite"])
    {
        for (NSDictionary * dict in _inviteList) {
            if ([[dict objectForKey:@"userId"] isEqualToString:[msg objectForKey:@"userId"]] &&
                [[dict objectForKey:@"content"] isEqualToString:[msg objectForKey:@"content"]] )
            {
                return YES;
            }
        }
    }
    else if ([type isEqualToString:@"merchant"])
    {
        for (NSDictionary * dict in _merchantList) {
            if ([[dict objectForKey:@"merchantId"] isEqualToString:[msg objectForKey:@"merchantId"]] &&
                [[dict objectForKey:@"title"] isEqualToString:[msg objectForKey:@"title"]] &&
                [[dict objectForKey:@"content"] isEqualToString:[msg objectForKey:@"content"]])
            {
                return YES;
            }
        }
    }
    else if ([type isEqualToString:@"url"])
    {
        for (NSDictionary * dict in _urlList) {
            if ([[dict objectForKey:@"title"] isEqualToString:[msg objectForKey:@"title"]] &&
                [[dict objectForKey:@"url"] isEqualToString:[msg objectForKey:@"url"]] )
            {
                return YES;
            }
        }
    }
    
    return NO;
}

@end
